import React, { useEffect, useState, createContext } from 'react';
import { Stack } from 'expo-router';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { StatusBar } from 'expo-status-bar';
import { AIAvatarPortal } from '../components/AIAvatarPortal';
import { initializeUILib } from '../theme/uiLib.config';
import { Colors } from 'react-native-ui-lib';
import { useAIStore } from '../store/ai';
import { config } from '../config';
import { IntroductionGuide } from '../components/IntroductionGuide';
import { View, Text } from 'react-native';
import { Audio } from 'expo-av';
import { soundPlayer } from '../utils/sound';
import { initStorage } from '../utils/storage';
import type { NativeStackNavigationOptions } from '@react-navigation/native-stack';


// 第一步初始化存储，这样才能继续使用
initStorage();

// 定义 Context 类型
interface ModalContextType {
  hasShownModal: boolean;
  setHasShownModal: (value: boolean) => void;
}

// 创建 Context
export const ModalContext = createContext<ModalContextType>({
  hasShownModal: false,
  setHasShownModal: () => {console.log('set ModalContext')},
});

// 加载屏幕组件
const LoadingScreen = () => (
  <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: Colors.background }}>
    <Text style={{ color: Colors.white }}>加载中...</Text>
  </View>
);

// 错误屏幕组件
const ErrorScreen = ({ error, onRetry }: { error: Error; onRetry: () => void }) => (
  <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: Colors.background }}>
    <Text style={{ color: Colors.white }}>出错了: {error.message}</Text>
    <Text style={{ color: Colors.white, marginTop: 10 }} onPress={onRetry}>
      点击重试
    </Text>
  </View>
);

export default function Layout() {
  const { initSpeechManager, loadHistory } = useAIStore();
  const [hasShownModal, setHasShownModal] = useState(false);
  const [showIntro, setShowIntro] = useState(true);
  const [isInitialized, setIsInitialized] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const initializeApp = async () => {
    try {
      setError(null);
      
      // 1. UI 初始化
      await initializeUILib();

      // 2. 音频系统初始化
      await Audio.setAudioModeAsync({
        allowsRecordingIOS: false,
        playsInSilentModeIOS: true,
        staysActiveInBackground: false,
        shouldDuckAndroid: true,
        playThroughEarpieceAndroid: false,
      });
      await soundPlayer.initsound();

      // 3. 语音管理器初始化
      initSpeechManager(config.api.appKey, config.api.accessKey);

      // 4. 加载历史记录
      await loadHistory();

      setIsInitialized(true);
    } catch (err) {
      console.error('初始化失败:', err);
      setError(err instanceof Error ? err : new Error('初始化失败'));
    }
  };

  useEffect(() => {
    initializeApp();
    return () => {
      soundPlayer.unload();
    };
  }, []);

  if (error) {
    return <ErrorScreen error={error} onRetry={initializeApp} />;
  }

  if (!isInitialized) {
    return <LoadingScreen />;
  }

  const stackOptions: { 
    initialRouteName: string; 
    screenOptions: NativeStackNavigationOptions;
  } = {
    initialRouteName: "index",
    screenOptions: {
      headerShown: false,
      contentStyle: {
        backgroundColor: Colors.background,
      },
      animation: 'slide_from_right',
    }
  };

  return (
    <ModalContext.Provider value={{ hasShownModal, setHasShownModal }}>
      <GestureHandlerRootView style={{ flex: 1, backgroundColor: Colors.background }}>
        <StatusBar style="light" />
        {showIntro ? (
          <IntroductionGuide onComplete={() => setShowIntro(false)} />
        ) : (
          <Stack {...stackOptions}>
            <Stack.Screen name="index" />
            <Stack.Screen name="BindAccount" />
            <Stack.Screen name="MyFamilyPoints" />
            <Stack.Screen name="MerchantDetail" />
          </Stack>
        )}
        <AIAvatarPortal />
      </GestureHandlerRootView>
    </ModalContext.Provider>
  );
} 